<template>
	<div class="echart" ref="myChartRef"></div>
</template>
  
<script setup>
import { ref, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { useEventListener } from '/@/jqkit/jqkComposables/useEvent'
import { debounce } from 'lodash';

const props = defineProps({
	dataSource: {
		type: Object,
		default: null,
	},
});

const title = ref('');
const xAxisData = ref([]);
const yAxisData = ref([]);
const myChartRef = ref(null);
let myChart = null;
let timer = null;

const handleDataSource = (obj) => {
	if (!obj) return;
	// console.log("当前组件接收数据源为：", obj);
	
	title.value = obj.title || '';
	xAxisData.value = obj.xAxisData || [];
	yAxisData.value = obj.yAxisData || [];

	nextTick(() => {
		initChart();
		resizeChart();
	});
};

// 监听 props.dataSource 的变化
watch(() => props.dataSource, (newVal) => {
	handleDataSource(newVal);
}, { immediate: true,  deep: true });

// 获取 series 数据
const getSeries = (yAxisData) => {
	return yAxisData.map((item) => ({
		name: item.name || '',
		type: 'line',
		smooth: item.smooth || false,
		data: item.data || [],
		lineStyle: {
			width: 1,
		},
	}));
};

// 获取 echart 配置项
const getOption = () => {
	return {
		title: {
			text: title.value,
		},
		tooltip: {
			trigger: 'axis',
		},
		legend: {
			data: yAxisData.value.map((item) => item.name),
		},
		grid: {
			left: '2%',
			right: '2%',
			bottom: '2%',
			containLabel: true,
		},
		toolbox: {
			feature: {
				saveAsImage: {},
			},
		},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: xAxisData.value,
		},
		yAxis: {
			type: 'value',
		},
		series: getSeries(yAxisData.value),
	};
};

// 初始化 echart 图表
const initChart = () => {
	if (!myChartRef.value) return;

	const chartDom = document.getElementById(myChartRef.value.id);
	if (!chartDom) return;

	echarts.dispose(chartDom);
	myChart = echarts.init(chartDom);
	const option = getOption();
	option && myChart.setOption(option);
};

// 重置 echart 尺寸
const resizeChart = debounce(() => {
	if (myChart) myChart.resize();
}, 200);
useEventListener(window, 'resize', resizeChart)
</script>

<style scoped lang="scss">
.echart {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100%;
	background-color: #fff;
}
</style>